package com.cby.library.base.web;

import android.util.Log;
import android.webkit.SslErrorHandler;

import com.cby.code.util.CbyLogUtils;
import com.cby.library.base.ssl.HttpsSSLSocketFactory;
import com.cby.library.base.ssl.HttpsX509TrustManager;

import java.io.IOException;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author ChenBaoyang
 * @description: CertifiUtils
 * @date 2021/12/1 09:51
 */
public class CertificateUtils {

    public static void onCertificateOfVerification(final SslErrorHandler handler, String url) {
        OkHttpClient.Builder builder = setCertificates(new OkHttpClient.Builder());
        Request request = new Request.Builder().url(url)
                .build();
        builder.build().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                CbyLogUtils.e("证书验证失败", e.getMessage());
                handler.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                CbyLogUtils.e("证书验证成功", response.body().string());
                handler.proceed();
            }
        });
    }

    private static OkHttpClient.Builder setCertificates(OkHttpClient.Builder client) {
        try {
            SSLSocketFactory sslSocketFactory = HttpsSSLSocketFactory.factory();
            X509TrustManager trustManager = new HttpsX509TrustManager();
            client.sslSocketFactory(sslSocketFactory, trustManager);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }
}
